import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:isolate';
import 'package:meta/dart2js.dart';

class AsyncDemo extends StatefulWidget {
	@override
	State<StatefulWidget> createState() {
		// TODO: implement createState
		return AsyncDemoState();
	}
}

class AsyncDemoState extends State<AsyncDemo> {

	String text = "Empty";
	String widgets = "";

	@override
	Widget build(BuildContext context) {
		// TODO: implement build
		return Scaffold(
			appBar: AppBar(title: Text("Async Demo"),
			),
			body: Center(
				child: _createBody(),
			),
		);
	}

	Widget _createBody() {
		return new Column(
			children: <Widget>[
				RaisedButton(
					child: Text("StartLoadData"),
					onPressed: () {
						_startLoadData();
					},
				),
				RaisedButton(
					child: Text("StopLoadData"),
					onPressed: () {

					},
				),
				Text(text),
			],
		);
	}

	_startLoadData() async {
		var url = "http://www.baidu.com";
		var response = await http.get(url);
		if (response.statusCode == 200) {
			String textToShow = response.body.replaceAll("\n", "");
			textToShow = textToShow.replaceAll("\r", "");
			setState(() {
			  text = textToShow;
			});
		}
	}


    // Isolate Demo
	loadData() async {
		ReceivePort receivePort = ReceivePort();
		await Isolate.spawn(dataLoader, receivePort.sendPort);

		// The 'echo' isolate sends its SendPort as the first message
		SendPort sendPort = await receivePort.first;

		String msg = await sendReceive(sendPort, "https://jsonplaceholder.typicode.com/posts");

		setState(() {
			widgets = msg;
		});
	}

	// The entry point for the isolate
	static dataLoader(SendPort sendPort) async {
		// Open the ReceivePort for incoming messages.
		ReceivePort port = ReceivePort();

		// Notify any other isolates what port this isolate listens to.
		sendPort.send(port.sendPort);

		await for (var msg in port) {
			String data = msg[0];
			SendPort replyTo = msg[1];

			String dataURL = data;
			http.Response response = await http.get(dataURL);
			// Lots of JSON to parse
			replyTo.send(response.body);
		}
	}

	Future sendReceive(SendPort port, msg) {
		ReceivePort response = ReceivePort();
		port.send([msg, response.sendPort]);
		return response.first;
	}
}